package com.example.community.rest;

import com.example.community.dto.FileDTO;
import com.example.community.provider.AliyunOssProvider;
import com.example.community.provider.UFileResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping(path = "/file")
@Slf4j
public class FileResource {
//    @Autowired
//    private UFileService uFileService;

    @Autowired
    private AliyunOssProvider aliyunOssProvider;

    @RequestMapping("/upload")
    @ResponseBody
    public Map<String,Object> upload(@RequestParam("image")MultipartFile file, HttpServletRequest request) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
//        MultipartFile file = multipartRequest.getFile("wangeditor-uploaded-image");

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
        String dataPath = dateFormat.format(new Date());
        String originFilename = file.getOriginalFilename();
        String suffix = originFilename.substring(originFilename.lastIndexOf("."));
        String filename = UUID.randomUUID().toString();
        String newName = filename + suffix;
        String fileUrl = dataPath + newName;
        Map<String,Object> map = new HashMap<>();
        try {
            UFileResult uFileResult = aliyunOssProvider.upload(file.getInputStream(), file.getContentType(), fileUrl);
            FileDTO fileDTO = new FileDTO();
            fileDTO.setSuccess(1);
            fileDTO.setUrl(uFileResult.getFileUrl());
            map.put("url",uFileResult.getFileUrl());
            return map;
        } catch (Exception e) {
            log.error("upload error", e);
            FileDTO fileDTO = new FileDTO();
            fileDTO.setSuccess(0);
            fileDTO.setMessage("上传失败");
            return map;
        }
    }
}
